package com.gy.nio;

import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * 缓冲区提供了两个核心方法
 * put:将数据存入缓冲区
 * get:或取缓冲区数据
 * <p>
 * 直接缓冲区和非直接缓冲区
 * 非直接缓冲区：痛殴allocate()方法分配缓冲区，将缓冲区建立在JVM的内存中
 * 直接缓冲区：通过allocateDircet()分配缓冲区，将缓冲区建立在物理内存中，效率更高
 */
public class BufferTest {


    @Test
    public void test1() {
        //初始化
        ByteBuffer buf = ByteBuffer.allocate(1024);
        System.out.println("--------------- allocate --------------- ");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        //写数据
        buf.put("abc".getBytes());
        System.out.println("--------------- put --------------- ");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        //切换模式
        buf.flip();
        System.out.println("--------------- flip --------------- ");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        //读数据
        byte[] dst = new byte[buf.limit()];
        buf.get(dst);
        System.out.println("--------------- get --------------- ");
        System.out.println(new String(dst, 0, dst.length));
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        //可重复读
        buf.rewind();
        System.out.println("--------------- rewind --------------- ");
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());

        //清空缓冲区 （但是缓冲区数据依然存在，数据处于被遗忘状态）
        buf.clear();
        System.out.println("--------------- clear --------------- ");
        System.out.println(new String(dst, 0, dst.length));
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.capacity());


    }

    @Test
    public void test2() {
        String str = "abcd";
        ByteBuffer buf = ByteBuffer.allocate(2014);

        //切换到读模式
        buf.flip();
        byte[] dst = new byte[buf.limit()];
        buf.get(dst, 0, 2);
        System.out.println(new String(dst, 0, 2));

        //标记
        buf.mark();
        buf.get(dst, 2, 2);
        System.out.println(new String(dst, 2, 2));

        //恢复到mark的位置
        buf.reset();
        System.out.println(buf.position());

        //判断缓冲区是否还有剩余数据
        if (buf.hasRemaining())
            System.out.println("剩余数据量：" + buf.remaining());

    }

    @Test
    public void test3() {

    }


}
